<?php
/**
 * 客户联系人控制器
 */

declare (strict_types = 1);

namespace app\controller\customer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Contact extends BaseController
{
    /**
     * 查看客户联系人列表
     */
    public function list()
    {
        $param = Request::param();
        
        try {
            $query = Db::name('customer_contact')
                ->alias('cc')
                ->leftJoin('customer c', 'cc.cid = c.id')
                ->field('cc.*, c.name as customer_name')
                ->where('cc.delete_time', 0);
            
            // 按客户ID筛选（可选参数）
            if (!empty($param['customer_id'])) {
                $query = $query->where('cc.cid', $param['customer_id']);
            }
            
            // 关键词搜索
            if (!empty($param['keywords'])) {
                $keywords = trim($param['keywords']);
                $query = $query->where('cc.name|cc.mobile|cc.email|cc.wechat', 'like', '%' . $keywords . '%');
            }
            
            // 分页参数
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            // 获取总数
            $total = $query->count();
            
            // 分页查询
            $list = $query
                ->order('cc.is_default', 'desc')
                ->order('cc.id', 'desc')
                ->page($page, $limit)
                ->select()
                ->each(function($item) {
                    $item['birthday'] = $item['birthday'] ? (int)$item['birthday'] : 0;
                    $item['create_time'] = (int)$item['create_time'];
                    $item['update_time'] = (int)$item['update_time'];
                    return $item;
                });
            
            // 使用统一的分页响应格式
            return $this->paginate($list->toArray(), $total, $page, $limit, 'success');
        } catch (\Exception $e) {
            return $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 查看单个客户联系人信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $contact = Db::name('customer_contact')
                ->where('id', $param['id'])
                ->find();
            
            if (empty($contact)) {
                return json(['code' => 404, 'msg' => '客户联系人不存在']);
            }
            
            // 确保时间字段是整数
            $contact['birthday'] = $contact['birthday'] ? (int)$contact['birthday'] : 0;
            $contact['create_time'] = (int)$contact['create_time'];
            $contact['update_time'] = (int)$contact['update_time'];
            
            // 反序列化家庭成员信息
            if (!empty($contact['family'])) {
                $contact['family'] = unserialize($contact['family']);
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $contact
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 新建客户联系人
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['customer_id'])) {
            return json(['code' => 400, 'msg' => '客户ID不能为空']);
        }
        
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '联系人姓名不能为空']);
        }
        
        // 处理生日时间
        $birthday = !empty($param['birthday']) ? strtotime($param['birthday']) : 0;
        
        // 处理家庭成员信息
        $family = [];
        $familyNameData = isset($param['family_name']) ? $param['family_name'] : '';
        $familyRelationsData = isset($param['family_relations']) ? $param['family_relations'] : '';
        $familyRemarksData = isset($param['family_remarks']) ? $param['family_remarks'] : '';
        
        if (!empty($familyNameData)) {
            foreach ($familyNameData as $key => $value) {
                if (!$value) {
                    continue;
                }
                $data = [];
                $data['family_name'] = $familyNameData[$key];
                $data['family_relations'] = $familyRelationsData[$key];
                $data['family_remarks'] = $familyRemarksData[$key];
                $family[] = $data;
            }
        }
        
        $serializedFamily = !empty($family) ? serialize($family) : '';
        
        $data = [
            'cid' => $param['customer_id'],
            'name' => $param['name'],
            'sex' => $param['sex'] ?? 0,
            'mobile' => $param['mobile'] ?? '',
            'qq' => $param['qq'] ?? '',
            'wechat' => $param['wechat'] ?? '',
            'email' => $param['email'] ?? '',
            'nickname' => $param['nickname'] ?? '',
            'department' => $param['department'] ?? '',
            'birthday' => $birthday,
            'address' => $param['address'] ?? '',
            'family' => $serializedFamily,
            'position' => $param['position'] ?? '',
            'admin_id' => $param['admin_id'] ?? 0,
            'is_default' => $param['is_default'] ?? 0,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            // 如果设置为默认联系人，需要将其他联系人设为非默认
            if ($data['is_default'] == 1) {
                Db::name('customer_contact')
                    ->where('cid', $param['customer_id'])
                    ->update(['is_default' => 0]);
            }
            
            $contactId = Db::name('customer_contact')->insertGetId($data);
            
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $contactId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑客户联系人
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['customer_id'])) {
            return json(['code' => 400, 'msg' => '客户ID不能为空']);
        }
        
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '联系人姓名不能为空']);
        }
        
        // 处理生日时间
        $birthday = !empty($param['birthday']) ? strtotime($param['birthday']) : 0;
        
        // 处理家庭成员信息
        $family = [];
        $familyNameData = isset($param['family_name']) ? $param['family_name'] : '';
        $familyRelationsData = isset($param['family_relations']) ? $param['family_relations'] : '';
        $familyRemarksData = isset($param['family_remarks']) ? $param['family_remarks'] : '';
        
        if (!empty($familyNameData)) {
            foreach ($familyNameData as $key => $value) {
                if (!$value) {
                    continue;
                }
                $data = [];
                $data['family_name'] = $familyNameData[$key];
                $data['family_relations'] = $familyRelationsData[$key];
                $data['family_remarks'] = $familyRemarksData[$key];
                $family[] = $data;
            }
        }
        
        $serializedFamily = !empty($family) ? serialize($family) : '';
        
        $data = [
            'id' => $param['id'],
            'cid' => $param['customer_id'],
            'name' => $param['name'],
            'sex' => $param['sex'] ?? 0,
            'mobile' => $param['mobile'] ?? '',
            'qq' => $param['qq'] ?? '',
            'wechat' => $param['wechat'] ?? '',
            'email' => $param['email'] ?? '',
            'nickname' => $param['nickname'] ?? '',
            'department' => $param['department'] ?? '',
            'birthday' => $birthday,
            'address' => $param['address'] ?? '',
            'family' => $serializedFamily,
            'position' => $param['position'] ?? '',
            'admin_id' => $param['admin_id'] ?? 0,
            'is_default' => $param['is_default'] ?? 0,
            'update_time' => time()
        ];
        
        try {
            // 如果设置为默认联系人，需要将其他联系人设为非默认
            if ($data['is_default'] == 1) {
                Db::name('customer_contact')
                    ->where('cid', $param['customer_id'])
                    ->where('id', '<>', $param['id'])
                    ->update(['is_default' => 0]);
            }
            
            Db::name('customer_contact')->update($data);
            
            return json(['code' => 0, 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '编辑失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除客户联系人（软删除）
     */
    public function del()
    {
        // 获取所有可能的参数来源
        $id = null;
        
        // 1. 尝试从路由参数获取（URL路径参数）
        $id = Request::param('id');
        
        // 2. 如果没有从路由参数获取到，尝试从查询字符串获取
        if (empty($id)) {
            $id = input('get.id');
        }
        
        // 3. 如果还没有获取到，尝试从POST数据获取
        if (empty($id)) {
            $id = input('post.id');
        }
        
        // 4. 最后尝试从原始请求数据获取
        if (empty($id)) {
            $param = Request::param();
            $id = isset($param['id']) ? $param['id'] : null;
        }
        
        // 记录调试信息
        \think\facade\Log::info('删除联系人参数: ' . json_encode(Request::param()) . ', 获取到的ID: ' . var_export($id, true));
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误: 未找到联系人ID']);
        }
        
        try {
            $contact = Db::name('customer_contact')
                ->where('id', $id)
                ->find();
            
            if (empty($contact)) {
                return json(['code' => 404, 'msg' => '客户联系人不存在']);
            }
            
            // 检查是否是默认联系人
            if ($contact['is_default'] == 1) {
                return json(['code' => 400, 'msg' => '默认联系人不能删除']);
            }
            
            Db::name('customer_contact')
                ->where('id', $id)
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 设置默认联系人
     */
    public function set_default()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['customer_id'])) {
            return json(['code' => 400, 'msg' => '客户ID不能为空']);
        }
        
        try {
            // 将该客户下的所有联系人设为非默认
            Db::name('customer_contact')
                ->where('cid', $param['customer_id'])
                ->update(['is_default' => 0]);
            
            // 将指定联系人设为默认
            Db::name('customer_contact')
                ->where('id', $param['id'])
                ->update([
                    'is_default' => 1,
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '设置成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '设置失败: ' . $e->getMessage()]);
        }
    }
}